package cn.itcast.consumer.web;


import cn.itcast.consumer.client.UserClient;
import cn.itcast.consumer.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 虎哥
 */
//@DefaultProperties(defaultFallback = "defaultFallback")
@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    private UserClient userClient;

    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id) {
        return userClient.queryById(id);
    }

//    @Autowired
//    private RestTemplate restTemplate;
//    @HystrixCommand(commandProperties = {
//            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
//    })
    /*@HystrixCommand(commandProperties = {
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "15000")
    })
//    @HystrixCommand
    @GetMapping("{id}")
    public String queryById(@PathVariable("id") Long id) {
        if(id == 1){
            throw new RuntimeException();
        }
        // 请求路径
        String url = "http://user-service/user/" + id;
        // 发起请求
        return restTemplate.getForObject(url, String.class);
    }*/

    public String defaultFallback(){
        return "别挤了!服务器快炸了！";
    }

//    int count = 0;// CAS compare and set

    // AtomicInteger num = new AtomicInteger(0);

    /**
     * 服务的发现的客户端。可以去拉取服务列表
     */
    /*
    @Autowired
    private DiscoveryClient discoveryClient;
    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id){
        // 拉取服务列表
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        // 负载均衡，从集合中挑选一个实例
//        int index = new Random().nextInt(instances.size());
//        count = count+1 % instances.size();
        ServiceInstance instance = instances.get(0);
        // 从实例中拿到host和port
        String host = instance.getHost();
        int port = instance.getPort();
        // 请求路径
        String url = String.format("http://%s:%d/user/%d", host, port, id);
        // 发起请求
        return restTemplate.getForObject(url, User.class);
    }*/
}